package cn.znzz.cjm.userdetails;

import cn.znzz.cjm.domain.LoginUser;
import cn.znzz.cjm.domain.Permission;
import cn.znzz.cjm.feign.IUserInfoFeignClient;
import cn.znzz.cjm.mapper.LoginUserMapper;
import cn.znzz.cjm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HrmUserdetailsService implements UserDetailsService {
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private IUserInfoFeignClient userInfoFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser = loginUserMapper.selectOne(loginUser);
        //调用system服务查询用户的其他基本信息 封装好  以便其他地方使用
        AjaxResult result = userInfoFeignClient.findUserInfo(loginUser.getId());
        System.out.println(result.isSuccess());
        if(result.isSuccess()){
            Object resultObj = result.getResultObj();
            //UserInfo userInfo = JSON.parseObject(JSON.toJSONString(resultObj), UserInfo.class);
            /**
             * 将用户的基本信息 放入一个地方
             * 1.上下文中   利用name字段  将用户信息放在name字段位置
             *  其他服务获取name字段的时候 实际上获取的就是用户的基本信息
             * 2.redis（推荐）
             */
            String key = "userinfo::"+username;
            redisTemplate.opsForValue().set(key,resultObj);
            System.err.println(key);
            System.out.println("-------------------");
            System.out.println(resultObj);
        }
        //查询用户的权限
        List<Permission> pers = loginUserMapper.findPermissionsByUserId(loginUser.getId());
        //封装权限
        ArrayList<SimpleGrantedAuthority> authors = new ArrayList<>();
        pers.stream().forEach(permission -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
            authors.add(authority);
        });
        User user = new User(loginUser.getUsername(), loginUser.getPassword(),authors );
        return user;
    }
}